<template>
  <div>
    <div class="buttons">
      <el-cascader
        placeholder="区域"
        :options="options"
        @active-item-change="handleItemChange"
        v-model="cityId"
        clearable
        :props="props"
      ></el-cascader>
      <el-button type="primary" @click="getRoll">查询</el-button>
      <el-button type="primary" @click="clear">清空</el-button>
      <el-button type="primary" @click="createForm('create')">新增</el-button>
      <template v-if="checkNum===1">
        <el-button type="primary" @click="createForm('update')" this.ruleForm>修改</el-button>
      </template>
      <el-button type="danger" @click="removeForm" v-if="checkNum >=1">删除</el-button>
    </div>
    <VTable
      v-if="tableData.code!==405"
      :tableData="tableData.data"
      :tableHeader="tableHeader"
      :tableHandle="tableHandle"
      :selectRow="selectRow"
      :tableSort="tableSort"
      :cellClick="cellClick"
      v-loading="listLoading">
    </VTable>
    <div class="page-wrap" v-if="tableData.data">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="tableData.data.size"
        layout="total, prev, pager, next, jumper"
        :total="tableData.data.total">
      </el-pagination>
    </div>
    <VForm :title="title" v-if="dialogVisible" moduleName="roll">
      <template v-if="dialogModle==='images'">
        <Roll :ruleForm="ruleForm" :formType="formType" :getTableData="getTableData"></Roll>
      </template>
      <template v-if="dialogModle==='city'">
        <City :imageId="imageId" :getTableData="getTableData"></City>
      </template>
    </VForm>
  </div>
</template>
<script>
  import VTable from '../../components/VTable.vue'
  import VForm from '../../components/VForm'
  import Roll from './Roll.vue'
  import axios from 'axios'
  import City from '../../view/index/City'
  import api from '../../store/api'
  var moment = require('moment')
  var format = require('../../util/util')
  import {mapState, mapGetters} from 'vuex'
  import * as types from '../../store/mutations-type'
  export default {
    data () {
      return {
        title: '新建',
        currentPage: 1,
        limit: 20,
        status: true,
        selection: [],
        listLoading: false,
        id: '',
        dialogModle: '',
        ruleForm: {
          imageName: '',
          imageType: '1',
          imagePath: '',
          imageLink: '',
          imageDesc: '',
          imageSort: '',
          showIndex: '1'
        },
        formType: 'create',
        tableHeader: [
          {prop: 'imageSort', label: '图片排序'},
          {prop: 'imageName', label: '图片名称', order: 'descending'},
          {prop: 'imageType', label: '图片类型', formatter: this.formatterType},
          {prop: 'imgPreView', label: '图片', formatter: this.formatterImg, type: 'image', width: 90},
          {prop: 'imagePath', label: '图片地址（点击链接可查看原图）', width: 380},
          {prop: 'imageLink', label: '跳转链接', width: 210},
          {prop: 'imageDesc', label: '图片描述'},
          {prop: 'cityName', label: '区域', formatter: this.formatterAddress},
          {prop: 'showIndex', label: '是否在首页显示', formatter: this.formatterStatus},
          {prop: 'createTime', label: '创建时间', width: 175, formatter: this.formatterCteatetime}
        ],
        cityId: [],
        cityName: '',
        flag: {
          a: '',
          b: ''
        },
        options: [{
          value: '28',
          label: '甘肃'
        }],
        props: {
          value: 'id',
          label: 'cityName'
        },
        tableHandle: [
          {
            text: '绑定区域', event: this.cityBind
          }]
      }
    },
    components: {
      VTable,
      VForm,
      Roll,
      City
    },
    methods: {
      cellClick (row, column, cell, event) {
        if (cell.cellIndex === 5) {
          window.open(row.imagePath)
        }
      },
      cityBind (index, obj) {
        this.dialogModle = 'city'
        this.imageId = obj.id
        this.$store.dispatch(types.ROLL_SHOW_FORM)
        this.title = '绑定区域'
      },
      /**
       * 时间格式化
       * @param row
       * @returns {string}
       */
      formatterCteatetime (row) {
        return moment(new Date(row.createTime)).format('YYYY-MM-DD hh:mm:ss')
      },
      /**
       * 性别转换
       * @param row
       * @returns {string}
       */
      formatterStatus (row) {
        return row.showIndex === 1 ? '是' : '否'
      },
      /**
       * 状态转义
       * @param row
       * @returns {string}
       */
      formatterType (row) {
        return row.imageType === 1 ? '轮播图' : row.imageType === 2 ? '品牌' : row.imageType === 3 ? '分类' : ''
      },
      /**
       * 区域合并
       * @param row
       * @returns {string}
       */
      formatterAddress (row) {
        if (row.cityPname && row.cityName) {
          return row.cityPname + ',' + row.cityName
        }
      },
      /**
       * 每页条数
       * @param val
       */
      handleSizeChange (val) {
        console.log(`每页 ${val} 条`)
      },
      /**
       * 翻页
       * @param val
       */
      handleCurrentChange (val) {
        this.currentPage = val
        this.getTableData()
      },
      getTableData () {
        this.$store.dispatch(types.ROLL_REQ_LIST, '?pageIndex=' + this.currentPage + '&pageSize=' + this.limit + '')
      },
      /**
       * 跳转到商家表单
       * @param handle
       */
      createForm (handle) {
        this.formType = handle
        this.dialogModle = 'images'
        if (handle === 'update') {
          this.title = '修改'
          this.getItem()
        } else {
          this.$store.dispatch(types.ROLL_SHOW_FORM)
          this.title = '新建'
          this.ruleForm = {
            imageName: '',
            imageType: '1',
            imagePath: '',
            imageLink: '',
            imageDesc: '',
            imageSort: '',
            showIndex: '1'
          }
        }
      },
      /**
       * 选中行处理
       * @param selection //总共选中行
       * @param row // 选中行
       */
      selectRow (selection, row) {
        this.$store.dispatch(types.ROLL_CHECK_NUM, selection.length)
        this.selection = selection
      },
      getItem () {
        axios.get(api.imagesGet + '/' + this.selection[0].id)
          .then(response => {
            const result = response.data
            if (result.success) {
              this.ruleForm.id = result.data.id
              this.ruleForm.imageSort = result.data.imageSort.toString()
              this.ruleForm.imageName = result.data.imageName
              this.ruleForm.imageType = result.data.imageType.toString()
              this.ruleForm.imagePath = result.data.imagePath
              this.ruleForm.imageLink = result.data.imageLink
              this.ruleForm.imageDesc = result.data.imageDesc
              this.ruleForm.showIndex = result.data.showIndex.toString()
              this.$store.dispatch(types.ROLL_SHOW_FORM)
              console.log(this.ruleForm)
            }
          })
      },
      /**
       * 根据id查询数据
       */
      getRoll () {
        this.currentPage = 1
        let para = {
          pageIndex: this.currentPage,
          pageSize: this.limit,
          cityId: this.cityId[1]
        }
        if (!this.cityId[1]) {
          delete para.cityId
        }
        para = format.formatString(para)
        this.$store.dispatch(types.ROLL_REQ_LIST, '?' + para)
      },
      clear () {
        this.cityId = []
        this.getTableData()
      },
      /**
       * 删除操作
       */
      removeForm () {
        var ids = this.selection.map(item => item.id).toLocaleString()
        this.$confirm('确认删除选中记录吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.listLoading = true
          let para = ids
          axios.delete(api.imagesDelete + '?ids=' + para).then((response) => {
            var result = response.data
            if (result.success) {
              this.listLoading = false
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            } else {
              this.$message.error({
                title: '错误',
                message: result.message
              })
            }
            this.getTableData()
          }, (err) => {
            this.$message.error({
              title: '错误',
              message: err.response.data.message
            })
            this.listLoading = false
          })
        })
      },
      /**
       * 表单初始化
       */
      initFormData () {
        for (var i in this.ruleForm) {
          this.ruleForm[i] = ''
        }
      },
      /**
       * 列表排序
       * @param column
       * @param prop
       * @param order
       */
      tableSort (column, prop, order) {
      },
      handleItemChange (val) {
        var length = val.length - 1
        if (val.length === 1) {
          this.options.map((item, index) => {
            if (item.id === val[length]) {
              this.flag.a = index
              return
            }
          })
          this.getCityLib(val[length])
            .then(result => {
              this.options[this.flag.a].children = result
            })
        }
      },
      getCityLib (id) {
        let url = api.cityLib
        url = id ? url + '?parentId=' + id : url
        return new Promise((resolve, reject) => {
          axios.get(url)
            .then(response => {
              const result = response.data
              if (result.success) {
                resolve(result.data)
              } else {
                reject(result)
              }
            })
        })
      }
    },
    updated () {
      if (this.tableData.code === 405) {
        this.$message.error({
          title: '错误',
          message: this.tableData.message
        })
      }
    },
    computed: {
      ...mapState({
        dialogVisible: state => state.roll.dialogVisible,
        checkNum: state => state.roll.checkNum
      }),
      ...mapGetters({
        tableData: 'roll_tableData'
      })
    },
    mounted () {
      this.getTableData()
      this.getCityLib()
        .then(result => {
          this.options = result
        })
    }
  }
</script>
